<template>
	<view class="detail-content">
		<swiper :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
			<swiper-item class="swiper-box" v-for="(item,index) in spu.images" :key="index">
				<image class="swiper-img" :src="item.imgUrl" mode=""></image>
			</swiper-item>
		</swiper>

		<view class="seckill" v-if="sku.seckillInfo">
			<view class="seckill-price">
				<view class="seckill-price-title">秒杀价
					<text class="seckill-price-prefix">¥</text>
					<text class="seckill-seckill-price" v-if="sku.price">{{ sku.seckillInfo.price }}</text></view>
				<view class="seckill-price-title">日常价
				<text class="normal-price-prefix">¥</text>
				<text class="seckill-normal-price" v-if="sku.price">{{ sku.price }}</text></view>
			</view>
		</view>
		<view class="goods-detail">
			<view class="price" v-if="!sku.seckillInfo">
				<text class="price-prefix">¥</text>
				<text v-if="sku.price">{{ sku.price }}</text>
			</view>
			<view class="goods-name">
				{{ spu.info.name }}
			</view>
		</view>

		<view class="goods-more-box">
			<view class="goods-more-item" @tap="showCouponPopup">
				<view class="goods-more-title">优惠</view>
				<view class="goods-more-content">
					<view style="display: inline;" v-for="(item,index) in couponList" :key="index" >
						<text class="discounts-coupon" v-if="item.minPoint === 0">{{ item.amount }}元无门槛</text>
						<text class="discounts-coupon" v-else>满{{ item.minPoint }}减{{ item.amount }}</text>
					</view>
					<view class="more" style="display: inline-block;float: right;">
						<uni-icons type="forward" size="12" color="#606060"></uni-icons>
					</view>
				</view>
			</view>
			<view class="goods-more-item" @tap="isShow = true">
				<view class="goods-more-title">选择</view>
				<view class="goods-more-content">已选:
					<text class="attrs" v-for="(data,idx) in sku.skuAttrs" :key="idx">
						<text>{{ ' ' + data + '; ' }}</text>
					</text>
					<view class="more" style="display: inline-block;float: right;">
						<uni-icons type="forward" size="12" color="#606060"></uni-icons>
					</view>
				</view>
			</view>
			<view class="goods-more-item">
				<view class="goods-more-title">送至</view>
				<view class="goods-more-content" v-if="defaultAddress.province">{{defaultAddress.province + defaultAddress.city + defaultAddress.region + defaultAddress.detailAddress }}</view>
				<view class="goods-more-content" v-else>请选择收货地址</view>
				<view class="more" style="display: inline-block;float: right;">
					<uni-icons type="forward" size="12" color="#606060"></uni-icons>
				</view>
			</view>
			<view class="goods-base-attr-box" @tap="showBaseAttrPopup">
				<view class="goods-more-title">参数</view>
				<view class="goods-more-content">
          <view class="base-attr-box" v-if="spuBaseAttr.length !== 0">
            <view class="base-attr-item" v-for="(item,index) in spuBaseAttr" :key="index">
              <text class="base-attr-value">{{ item.attrValue.join(',') }}</text>
              <text class="base-attr-name">{{ item.attrName }}</text>
            </view>
          </view>
          <view v-else>
            暂无参数信息
          </view>
        </view>
				<view class="more" style="display: inline-block;float: right;">
					<uni-icons type="forward" size="12" color="#606060"></uni-icons>
				</view>
			</view>
		</view>

		<view class="spu-detail">
			<module-card card-title="商品介绍"></module-card>
			<view style="margin-top: 20rpx;">
				<view v-html="spu.desc.detail"></view>
			</view>
		</view>

		<view class="detail-foot">
			<view class="icon-item-box">
				<view class="iconfont icon-shangpinduibi"></view>
				<view class="icon-text">对比</view>
			</view>
		  <view class="detail-left">
        <view class="icon-item-box">
          <view class="iconfont icon-shoucang"></view>
          <view class="icon-text">收藏</view>
        </view>
        <view class="icon-item-box" @tap="toCart">
          <view class="iconfont icon-31gouwuche"></view>
          <view class="icon-text">购物车</view>
        </view>
      </view>
			<view class="add-cart" @tap="showBox(1)">
				加入购物车
			</view>
			<view class="buy-now" @tap="showBox(2)">
				立即购买
			</view>
		</view>

		<uni-popup ref="popup" type="bottom">
			<view class="coupon-box-title">优惠</view>
				<view class="coupon-box">
					<view class="coupon-content">
						<coupon-list :spuId="spuId"></coupon-list>
					</view>
				</view>
		</uni-popup>


		<uni-popup ref="attrPopup" type="bottom">
			<view class="attr-box-title">参数信息</view>
			<view class="attr-popup-content">
				<view class="popup-attr-item" v-for="(item,index) in spuBaseAttr" :key="index">
          <view class="popup-attr-name">{{ item.attrName }}</view>
          <view class="popup-attr-value">{{ item.attrValue.join(',') }}</view>
        </view>
			</view>
		</uni-popup>

		<!-- todo 组件替换 -->
		<view class="pop" v-show="isShow">
			<!-- @touchmove.stop.prevent 取消默认行为，可以做到蒙层弹出禁止页面滑动 -->
			<view class="pop-mask" @tap="hiddenBox()" @touchmove.stop.prevent=''></view>
			<view class="pop-box" :animation="animationData" @touchmove.stop.prevent=''>
				<view class="pop-content-box" >
					<view class="pop-box-header">
						<image v-if="sku.cover" class="pop-img" :src="sku.cover" mode=""></image>
						<image v-else class="pop-img" :src="spu.info.mainImg" mode=""></image>
						<view class="pop-box-header-r">
							<view class="price">
								<text class="price-prefix">¥</text>
								<text v-if="sku.seckillInfo">{{ sku.seckillInfo.price }}</text>
								<text v-else>{{ sku.price }}</text>
							</view>
							<view>
								<view v-if="selectedSkuId">
									<text class="selected">已选:</text>
									<text class="attr-str">{{ attrStr }}</text>
								</view>
								<view v-else>
									<text class="selected">请选择</text>
								</view>
							</view>
						</view>
					</view>
					<view class="attr-scroll">
						<scroll-view scroll-y="true">
							<view class="attr-scroll-item">
								<view class="attr-group" v-for="(item,index) in spu.spuSaleAttrs" :key="index">
									<view class="group-title">{{ item.attrName }}</view>
									<view class="attr-vals">
										<view
											@tap="handleClickAttr(e,index)"
											class="attr-value"
											:class="selectedAttr.findIndex(x => x.attrValue === e.attrValue) != -1 ? 'attr-value-active':''"
											v-for="(e,idx) in item.attrValueWithSkuIds"
											:key="idx">
											{{ e.attrValue }}
										</view>
									</view>
								</view>
							</view>
							<view class="pop-num">
								<view>购买数量</view>
								<uni-number-box :min="1" v-model="buyNum"></uni-number-box>
							</view>
						</scroll-view>
					</view>
					<view class="pop-confirm" v-if="buyType === 1" @tap="confirm">确认</view>
					<view class="pop-confirm" v-if="buyType === 2" @tap="confirm">立即购买</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import CouponList from '@/components/common/CouponList.vue'
	import ModuleCard from '@/components/common/ModuleCard.vue'
	import $http from '@/common/api/request.js'
	import uniNumberBox from '@/uni_modules/uni-number-box/components/uni-number-box/uni-number-box.vue'
	export default {
		components: {
			ModuleCard,
			uniNumberBox,
			CouponList
		},
		data() {
			return {
				isShow: false,
				animationData: {},
				spuId: '',
				spu: {},
				attrStr: '',
				selectedSkuId:'',
				selectedAttr:[],
				defaultSkuAttr: [],
        defaultAddress: {},
				sku:{},
				buyNum: 1,
				// 1 加入购物车 2 直接购买 3 商品秒杀
				buyType: 1,
				couponList: [],
        spuBaseAttr: []
			}
		},
		onLoad(options) {
			this.selectedSkuId = options.skuId
			this.initData()
      this.getDefaultAddress()
		},
		methods: {
			showBaseAttrPopup() {
				this.$refs.attrPopup.open()
			},
			showCouponPopup() {
				this.$refs.popup.open()
			},
      getSpuBaseAttr() {
        $http.request({
          url: `/product/productAttrValue/listBySpuId/${this.spuId}`,
          loading: true
        }).then(res => {
            if (res.success) {
              this.spuBaseAttr = res.data
            }
        })
      },
			initData() {
				$http.request({
					url: `/product/sku/getById/${this.selectedSkuId}`,
          loading: true
				}).then(res => {
					this.sku = res.data
					this.defaultSkuAttr = res.data.attrValues
					this.spuId = this.sku.spuId
					this.getSpuDetail()
          this.getSpuBaseAttr()
					this.getCoupon()
				})
			},
			getCoupon() {
				$http.request({
					url: `/coupon/coupon/${this.spuId}`
				}).then(res => {
					if(res.success) {
						this.couponList = res.data
						if(this.couponList > 10) {
							this.couponList = this.couponList.slice(0,10)
						}
					}
				})
			},
      getDefaultAddress() {
        $http.request({
          url: `/member/address/default`
        }).then(res => {
          if(res.success) {
            this.defaultAddress = res.data
          }
        })
      },
			toCart() {
				uni.switchTab({
					url: '/pages/cart/cart'
				})
			},
			getSpuDetail() {
				$http.request({
					url: '/product/spu/getById/' + this.spuId,
          loading: true
				}).then(res => {
					if (res.success) {
						res.data.desc.detail = res.data.desc.detail.replaceAll("<img",
							"<img style='max-width:100%'")
						this.spu = res.data
						// 初始化 sku 数据
						let attrs = this.defaultSkuAttr.map((item,index) => {
							return {
								attrValue: item,
								groupIndex: index,
								skuIds: this.spu.spuSaleAttrs[index].attrValueWithSkuIds.find(e => item === e.attrValue).skuIds
							}
						})
						attrs.forEach((item,index) => {
							this.handleClickAttr(item,index)
						})
					}
				})
			},
			handleClickAttr(attr,index) {
				let idx = this.selectedAttr.findIndex(item => item.attrValue === attr.attrValue)
				if(idx === -1) {
					this.selectedAttr = this.selectedAttr.filter(item => item.groupIndex !== index)
					this.selectedAttr.push({...attr,groupIndex:index})
					let skuIdsArr = this.selectedAttr.map(item => item.skuIds)
					let intersection = skuIdsArr.reduce((acc, cur) =>
					    acc.filter(value => cur.includes(value))
					  )
					if(intersection.length === 1) {
						this.selectedSkuId = intersection[0]
						this.attrStr = this.selectedAttr.map(item => item.attrValue).join(',')
						$http.request({
							url: `/product/sku/getById/${intersection[0]}`,
              loading: true
						}).then(res => {
							if (res.success) {
                this.sku = res.data
              }
						})
					}
				} else {
					this.selectedAttr.splice(idx,1)
					this.sku = {}
					this.selectedSkuId = undefined
					this.attrStr = ''
				}
			},
			confirm() {
        if(!this.selectedSkuId) {
          uni.showToast({
            duration: 5000,
            title: '请选择商品',
            icon: 'none'
          })
          return
        }
				if(this.buyType === 1) {
					$http.request({
						url: `/cart/cart/add?skuId=${this.selectedSkuId}&num=${this.buyNum}`,
						method:'POST'
					}).then(res => {
						if (res.success) {
              this.isShow = false
              uni.showToast({
                duration: 5000,
                title: '加入购物车成功',
                icon: 'none'
              })
            }
					})
					return
				}
        if (this.buyType === 2) {
          uni.navigateTo({
            url: `/pages/order/confirm-order?skuId=${this.selectedSkuId}&num=${this.buyNum}`
          })
          return;
        }
				// 秒杀
				if(this.sku.seckillInfo) {
					let seckillInfo = this.sku.seckillInfo
					let data = {
						seckillId:seckillInfo.seckillId,
						skuId: this.sku.id,
						randomCode: seckillInfo.randomCode,
						num: this.buyNum
					}
					$http.request({
						url: `/coupon/seckill/submit`,
						method:'POST',
						data: data
					}).then(res => {
						this.isShow = false
					})
					return
				}
			},
			showBox(buyType) {
				this.buyType = buyType
				let animation = uni.createAnimation({
					duration: 300
				});
				animation.translateY(1000).step()
				this.animationData = animation.export()
				setTimeout(() => {
					this.isShow = true
					animation.translateY(0).step()
					this.animationData = animation.export()
				}, 100)
			},
			hiddenBox() {
				let animation = uni.createAnimation({
					duration: 300
				});
				animation.translateY(1000).step()
				this.animationData = animation.export()
				setTimeout(() => {
					this.isShow = false
					animation.translateY(0).step()
					this.animationData = animation.export()
				}, 100)
			}
		}
	}
</script>

<style scoped>

	.coupon-box {
		height: 900rpx;
		background-color: #FFF;
		border-radius: 15rpx;
		padding: 20rpx 10rpx;
		overflow: scroll;
	}

	.coupon-box-title {
		padding: 10rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		width: 100%;
		position: fixed;
		text-align: center;
		height: 60rpx;
		font-weight: 600;
		background-color: #FFF;
		z-index: 999;
	}

	.attr-box-title {
		padding: 10rpx 0;
		display: flex;
		flex-direction: column;
		justify-content: center;
		width: 100%;
		position: fixed;
		text-align: center;
		height: 60rpx;
		font-size: 30rpx;
		background-color: #F1F1F1;
		z-index: 999;
	}

	.coupon-content {
		margin-top: 80rpx;
	}

	swiper {
		width: 100%;
		height: 750rpx;
		background-color: #FFFFFF;
	}

	.seckill-price {
		display: flex;
		flex-direction: column;
		justify-content: center;
		height: 100%;
	}

	.seckill-price-title {
		color: #FFDDBD;
		font-size: 22rpx;
		font-weight: 400;
	}

	.seckill-price-prefix {
		font-size: 22rpx;
		font-weight: 600;
		margin-left: 10rpx;
	}

	.seckill-seckill-price {
		color: #F2F2F2;
		font-size: 34rpx;
		font-weight: 800;
	}

	.normal-price-prefix {
		font-size: 20rpx;
		font-weight: 500;
		margin-left: 10rpx;
	}

	.seckill-normal-price {
		color: #F2F2F2;
		font-size: 28rpx;
		font-weight: 600;
	}

	.seckill {
		width: 100%;
		height: 100rpx;
		background-color: #FA4E24;
		padding: 10rpx;
	}

	.pop-box-header {
		display: flex;
	}

	.pop-box-header-r {
		display: flex;
		flex-direction: column;
		justify-content: flex-end;
		margin-left: 20rpx;
	}

	.goods-name {
		font-weight: bold;
		font-size: 29rpx;
	}

	.detail-content {
		background-color: #F2F2F2;
	}

	.swiper-img {
		width: 100%;
		height: 700rpx;
	}

	.goods-detail {
		font-weight: bold;
		font-size: 26rpx;
		padding: 10rpx 20rpx;
		background-color: #FFFFFF;
	}

	.price {
		color: #F1280D;
		font-weight: bold;
		font-size: 38rpx;
	}

	.price-prefix {
		font-size: 26rpx;
	}

	.detail-foot {
		height: 100rpx;
		padding-bottom: 30rpx;
		background-color: #FFFFFF;
		border-top: 3rpx solid #F7F6F6;
		position: fixed;
		bottom: 0;
		left: 0;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

  .detail-left {
    width: 40%;
    display: flex;
  }

	.detail-foot .iconfont {
		font-size: 40rpx;
		padding: 10rpx;
		border-radius: 100%;
		color: #666666;
		font-weight: 550;
		text-align: center;
		margin: 0 10rpx;
	}

	.icon-item-box {
		display: flex;
		flex-direction: column;
		align-items: center;
	}

	.icon-text {
		font-size: 16rpx;
		font-weight: 500;
		color: #666666;
	}

	.add-cart {
		width: 300rpx;
		text-align: center;
		height: 56rpx;
		font-size: 24rpx;
		font-weight: 800;
		border-radius: 40rpx;
		line-height: 56rpx;
		padding: 6rpx 30rpx;
		background-color: #FFC10D;
		color: #FFFFFF;
	}

	.buy-now {
		width: 300rpx;
		text-align: center;
		height: 56rpx;
		font-size: 24rpx;
		font-weight: 800;
		border-radius: 40rpx;
		line-height: 56rpx;
		margin: 0 15rpx;
		padding: 6rpx 30rpx;
		background-color: #F3290C;
		color: #FFFFFF;
	}

	.pop {
		position: fixed;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		z-index: 9;
	}

	.pop-mask {
		position: absolute;
		left: 0;
		top: 0;
		width: 100%;
		height: 100%;
		background-color: rgba(0, 0, 0, 0.3);
	}

	.pop-box {
		position: absolute;
		left: 0;
		bottom: 0;
		width: 100%;
		height: 560px;
		border-top-left-radius: 10px;
		border-top-right-radius: 10px;
		background-color: white;
	}

	.pop-img {
		width: 200rpx;
		height: 200rpx;
	}

	.pop-content-box {
		padding: 30rpx;
	}

	.pop-confirm {
		line-height: 66rpx;
		color: #FFFFFF;
		text-align: center;
		margin: 0 auto;
		font-weight: 800;
		font-size: 26rpx;
		margin-bottom: 50rpx;
		background-color: #F3290C;
		border-radius: 50rpx;
		width: 95%;
		left: 0;
		right: 0;
		position: absolute;
		bottom: 0;
	}

	.pop-confirm-not-stock {
		background-color: #F2F2F2;
		color: #262626;
	}

	.pop-num {
		margin-top: 50rpx;
		display: flex;
		justify-content: space-between;
	}

	.attr-group {
		margin-top: 20rpx;
	}

	.selected {
		font-size: 24rpx;
		color: #8C8C8C;
	}

	.attr-str {
		font-size: 25rpx;
		margin-left: 10rpx;
	}

	.group-title {
		font-weight: bold;
	}

	.attr-scroll {
		margin-top: 20rpx;
	}

	.attr-vals {
		margin-top: 20rpx;
		display: flex;
		justify-content: flex-start;
	}

	.attr-value {
		background-color: #F2F2F2;
		color: #262626;
		font-size: 24rpx;
		text-align: center;
		padding: 10rpx 30rpx;
		border-radius: 10rpx;
		margin: 0 12rpx;
	}

	.attr-value-active {
		background-color: #FCECEB;
		border: 1rpx solid #F1280D;
		color: #F1280D;
	}

	.discounts-title {
		font-weight: 600;
		font-size: 24rpx;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		width: 60rpx;
	}

	.discounts-content {
		padding: 10rpx 10rpx;
		display: flex;
	}

	.discounts-coupon {
		padding: 0 8rpx;
		font-size: 18rpx;
		color: #F1280D;
		border: 1rpx solid #F1280D;
		margin: 0 10rpx;
	}

	.goods-more-box {
		margin-top: 20rpx;
		border-radius: 20rpx;
		background-color: #FFFFFF;
		padding: 10rpx 20rpx;
	}

	.goods-more-item {
		display: flex;
		height: 80rpx;
		line-height: 80rpx;
	}

  .goods-base-attr-box {
    display: flex;
    height: 80rpx;
  }

	.goods-more-title {
		width: 70rpx;
		font-size: 22rpx;
		white-space: nowrap;
		color: #7F7F7F;
	}

	.goods-more-content {
		width: 100%;
		font-size: 24rpx;
		font-weight: 400;
		margin-left: 10rpx;
	}

	.spu-detail {
		margin-top: 20rpx;
		background-color: #FFFFFF;
		padding: 10rpx 0;
	}

  .base-attr-box {
    width: 80%;
    height: 70rpx;
    overflow: hidden;
  }

  .base-attr-item {
    display: inline-flex;
    overflow: hidden;
    height: 70rpx;
    justify-content: space-between;
    white-space: nowrap;
    flex-direction: column;
  }

  .base-attr-item:not(:first-child) {
    margin-left: 30rpx;
  }

  .base-attr-name {
    color: #878787;
  }

  .base-attr-value {
  }

  .attr-popup-content {
    height: 900rpx;
    background-color: #FFF;
    border-radius: 15rpx;
    padding: 20rpx 20rpx;
    overflow: scroll;
  }

  .popup-attr-item {
    display: flex;
    height: 60rpx;
    line-height: 60rpx;
    margin-top: 10rpx;
    font-size: 28rpx;
  }

  .popup-attr-name {
    color: #878787;
    width: 160rpx;
    overflow: hidden;
    text-overflow: ellipsis;
  }

  .popup-attr-value {
    margin-left: 10rpx;
  }

</style>
